<template>
<div class="login-box">
    <van-overlay :show="show" @click="show = false" />
    <van-loading size="24px" type="spinner"  vertical>数据加载中...</van-loading>
    </div>
</template>

<script>


	import { mapState, mapActions } from 'vuex'

    import wx from 'weixin-js-sdk';
    export default {
        name: 'Login',
        data(){
            return{
                show:true
            }
        },
		computed: mapState({
			application: state => state.application.systemInfo,
			userId: state => state.login.userId,
			loginInfo: state => state.login.loginInfo,
			isLogin: state => state.login.isLogin,
			wxInfo:state => state.login.wxInfo,
			redirectFullPath:state => state.login.redirectFullPath
		}),
        created: function () {
            //this.jsSDKConfig();
            this.wxLogin();
           
        },
        methods: {
            wxLogin:function(){
				var openId = this.$route.query.openId;
                openId = "oTz641EOpb6hJw-SRHb7wf8Rtir2";
				if(openId == '' || openId == undefined){
					this.getWxLoginUrl();
				}
				this.ssoLogin();

            },
            getWxLoginUrl(){
                var returnUrl = encodeURIComponent(window.location.href);
                //console.log(returnUrl);
                 // 上面的请求也可以这样做
                this.axios.get('/api/weixin/authorize?returnUrl='+returnUrl)
                .then(function (response) {
					window.location.href = response.data;
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
            ssoLogin(){
				var that = this;
                var openId = this.$route.query.openId;
                openId = "oTz641EOpb6hJw-SRHb7wf8Rtir2";
				if(openId != undefined && open != ''){
					// 上面的请求也可以这样做
					let data = {'openId': openId};
					
					that.axios.post('/wxlogin',JSON.stringify(data))
					.then(function (response) {
                        console.log(response.data);
						//将登录后的数据存储到客户端，以便下次请求时使用
						that.$store.commit("login/setUserId",response.data.userId);
						that.$store.commit('login/setLoginInfo',response.data.loginInfo);
    
                        var loginInfo = response.data.loginInfo;
                        //设置sessionStorage
                        sessionStorage.setItem('access_token',loginInfo.access_token);
                        //设置sessionStorage
                        sessionStorage.setItem('refresh_token',loginInfo.refresh_token);

						//获取用户微信信息
                        //that.getWxUser();
                         that.$router.replace("/expense/book");
                        
					})
					.catch(function (error) {
						console.log(error);
					});
				}
				 
            },
            getWxUser(){
				var openId = this.$route.query.openId;
				var that = this;
                 // 上面的请求也可以这样做
                this.axios.get('/api/weixin/getUserInfoByOpenId?openId='+openId)
                .then(function (response) {
					//首先判断是否关注，如果为关注就提示用户去关注
					var resultObj = JSON.parse(response.data.data);
					var subscribe = resultObj.weixinInfo.subscribe;
					if(!subscribe){
						that.$dialog.confirm({
							title: '微信公众号关注提示',
							message: '您未关注公众号，请先关注，否则无法使用相关功能',
							confirmButtonText:'去关注',
							confirmButtonColor:'#5868d4',
							cancelButtonText:'算了吧',
						})
						.then(() => {
							window.location.href = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzU2ODg0NDM2Nw==#wechat_redirect";
						})
						.catch(() => {
							that.$router.replace("/share");
						});
					}
					
					//存储用户微信信息,以便页面使用
					that.$store.commit('login/setWxInfo',resultObj.weixinInfo);
                    that.$store.commit('login/setIsLogin',true);


                    //get redirectFullPath url;
                    var redirectFullPath = that.redirectFullPath;
                    if(redirectFullPath != "" && redirectFullPath != undefined){
                        that.$router.replace(redirectFullPath);
                    }else{
                        that.$router.replace("/expense/book");
                    }

                })
                .catch(function (error) {
                    console.log(error);
                });
            },
            
            jsSDKConfig(){
                var url = encodeURIComponent(window.location.href.split('#')[0]);
                this.axios.get('/api/weixin/getJsConfig?url='+url)
                .then(function (response) {
					var jsConfig = response.data.data;
					jsConfig = JSON.parse(jsConfig);
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: jsConfig.appId, // 必填，公众号的唯一标识
                        timestamp: jsConfig.timestamp, // 必填，生成签名的时间戳
                        nonceStr: jsConfig.nonceStr, // 必填，生成签名的随机串
                        signature: jsConfig.signature,// 必填，签名
                        jsApiList: ['hideAllNonBaseMenuItem','onMenuShareAppMessage','updateAppMessageShareData','showMenuItems'] // 必填，需要使用的JS接口列表
                    });
                    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                        wx.hideAllNonBaseMenuItem();
                        // wx.showMenuItems({
                        //     menuList: ['menuItem:share:appMessage','menuItem:share:timeline'] // 要显示的菜单项，所有menu项见附录3
                        // });
                        // wx.onMenuShareAppMessage({ 
                        //     title: '一路向北', // 分享标题
                        //     desc: '小功能', // 分享描述
                        //     link: encodeURIComponent(window.location.href.split('?')[0]), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        //     imgUrl: '', // 分享图标
                        //     type: '', // 分享类型,music、video或link，不填默认为link
                        //     dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        //     success: function () {
                        //     // 设置成功
                        //     }
                        // })
                    });
                    
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
        }
    }
</script>

<style scoped>
.login-box{
    background-color: white;
    position: fixed;
    left: 0px;
    right: 0px;
    bottom: 0px;
    top: 0px;
    padding-top: 50%;
    color: white;
}
.van-loading{
    z-index: 2;
}
.van-overlay{
    background-color: #5868d4;
}
</style>